<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="职位名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-select
            v-model="queryParams.enabled"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <el-button
          v-hasPerm="['sys:post:create']"
          type="success"
          @click="handleOpenDialog(undefined)"
        >
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['sys:post:delete']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        default-expand-all
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="postName" label="职位名称" min-width="200" />
        <el-table-column
          prop="postLevel"
          label="职级"
          width="150"
          align="center"
        >
          <template #default="scope">
            <DictLabel v-model="scope.row.postLevel" code="post_level" />
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:post:create']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(undefined)"
            >
              <template #icon>
                <Plus />
              </template>
              新增
            </el-button>
            <el-button
              v-hasPerm="['sys:post:modify']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:post:delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form
        ref="postFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="职位名称" prop="postName">
          <el-input v-model="formData.postName" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职级" prop="postLevel">
          <Dict v-model="formData.postLevel" code="post_level" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="职位状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Post",
  inheritAttrs: false,
});

import PostAPI, {
  PostPageVO,
  PostForm,
  PostPageQuery,
} from "@/api/system/post";
import { useDictStore } from "@/store";

const dictStore = useDictStore();
const queryFormRef = ref(ElForm);
const postFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const tableData = ref<PostPageVO[]>();
const dialog = reactive({
  title: "",
  visible: false,
});

const queryParams = reactive<PostPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const formData = reactive<PostForm>({
  enabled: 1,
  sort: 1,
});

const rules = reactive({
  postName: [{ required: true, message: "职位名称不能为空", trigger: "blur" }],
  postLevel: [{ required: true, message: "职级不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

/** 查询职位 */
function handleQuery() {
  loading.value = true;
  PostAPI.getPage(queryParams)
    .then((data) => {
      tableData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开职位弹窗
 *
 * @param postId 职位ID
 */
async function handleOpenDialog(postId?: number) {
  dialog.visible = true;
  if (postId) {
    dialog.title = "修改职位";
    PostAPI.getFormData(postId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增职位";
  }
}

/** 提交职位表单 */
function handleSubmit() {
  postFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const postId = formData.id;
      if (postId) {
        PostAPI.modify(postId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        PostAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 删除职位 */
function handleDelete(postId?: number) {
  const postIds = postId ? [postId] : ids.value;

  if (!postIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      PostAPI.deleteByIds(postIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;

  postFormRef.value.resetFields();
  postFormRef.value.clearValidate();

  formData.id = undefined;
  formData.enabled = 1;
  formData.sort = 1;
}

onMounted(() => {
  handleQuery();
});
</script>
